package com.yaohuan;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author YaoHuan
 * @ClassName UploadFileServlet
 * @Description 上传文件
 * @Date 2022/11/24 6:29
 */
public class UploadFileServlet extends HttpServlet {
    //servlet处理文件
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        // 判断是否为multipart/form-data
        if (!ServletFileUpload.isMultipartContent(request)) {
            request.setAttribute("message", "必须为multipart/form-data数据");
        }else {
            // 配置FileItemFactory工厂
            FileItemFactory factory = new DiskFileItemFactory();
            // 创建用于解析数据的工具类ServletFileUpload类
            ServletFileUpload upload = new ServletFileUpload(factory);
            // 防止上传文件名称乱码
            upload.setHeaderEncoding("UTF-8");
            // 构造临时路径来存储上传的文件
            String uploadPath = "D:\\project\\maven-demo\\upload";
            // 如果目录不存在则创建
            File uploadDir = new File(uploadPath);
            if (!uploadDir.exists()) {
                uploadDir.mkdir();
            }
            try {
                // 解析请求的内容提取文件数据
                List<FileItem> formItems = upload.parseRequest(request);
                if (formItems != null && formItems.size() > 0) {
                    // 迭代表单数据，判断每个表单项是普通类型还是上传的文件
                    for (FileItem item : formItems) {
                        //上传的数据为文件的表单项处理方式
                        if (!item.isFormField()) {
                            //文件名
                            String fileName = item.getName();
                            System.out.println("文件名："+fileName);
                            // 保存的路径
                            String filePath = uploadPath + File.separator + fileName;
                            System.out.println(filePath);
                            // 保存文件到硬盘
                            File storeFile = new File(filePath);
                            item.write(storeFile);
                            request.setAttribute("message", "文件上传成功!");
                        }
                    }
                }
            } catch (Exception ex) {
                request.setAttribute("message", "错误信息: " + ex.getMessage());
            }
            // 跳转到 message.jsp
            request.getRequestDispatcher("/message.jsp").forward(request, response);
        }
    }

}
